/*
 * Copyright 2011-2012 Redia A/S
 * 
 * This file is part of Redias Library App for Android.
 *
 *  Redia Library App for Android is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redia Library App for Android is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redia Library App for Android.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.libraryapp;

import java.util.Observable;
import java.util.Observer;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import dk.redia.lib.config.LibraryAppConfig;
import dk.redia.lib.config.RediaConfig;
import dk.redia.lib.log.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import dk.redia.lib.model.InfoGalleriModel;
import dk.redia.lib.net.ImageCache;
import dk.redia.lib.utils.AppApplication;
import dk.redia.lib.utils.AppConfiguration;
import dk.redia.lib.utils.VersionUtils;
import dk.redia.lib.xmlrpc.XmlRpcClientResultListener;
import dk.redia.lib.xmlrpc.XmlRpcResultDumper;
import dk.redia.libraryapp.authentication.Authentication;
import dk.redia.libraryapp.utils.ResourceUtils;
import dk.redia.libraryapp.xmlrpc.library.XmlRpcClient;

public class LibraryAppActivity extends Activity {
	
	private static final String logTag = "LibraryAppActivity";
	//private GoogleAnalyticsTracker tracker;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //tracker = GoogleAnalyticsTracker.getInstance();
        //tracker.startNewSession("UA-34254449-1", 20, this);
        //tracker.trackPageView("/splashscreen");        
        
        String version = "0.0.0";
        try {
			version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
		} catch (NameNotFoundException e1) {
			Log.e(logTag, "Failed to retrieve version from manifest: " + e1.getMessage() + ". Using default.");
		}
        VersionUtils.setVersion(version);
        VersionUtils.setVersionNickName(getResources().getString(R.string.versionNickName));
        AppApplication.setApplicationContext(getApplicationContext());
        AppConfiguration.setAppConfiguration(new AppConfiguration() {
			

        	private boolean productionMode = getResources().getInteger(R.integer.productionMode) > 0;
        	
        	public void setProductionMode(boolean productionMode) {
        		this.productionMode = productionMode;
        		Authentication.getInstance().setAuthenticated(false);
        	}
        	
        	public boolean getProductionMode() {
        		return this.productionMode;
        	}

        	
			@Override
			public int getInfoGalleriModelRefreshInterval() {
				return getApplicationContext().getResources().getInteger(R.integer.infoGalleriModelRefreshInterval);
			}
			
			@Override
			public String getGalleryId() {
				return getApplicationContext().getResources().getString(R.string.galleryId);
			}
			
			@Override
			public String getCustomerId() {
				return getApplicationContext().getResources().getString(R.string.customerId);
			}
			
			@Override
			public String getApiKey() {
				return LibraryAppConfig.getLibraryApiKey(getCustomerId());
			}

			@Override
			public String getContentLanguage() {
				return getString(R.string.contentLanguage); 
			}

			@Override
			public void setContentLanguage(String language) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void setUiLanguage(String language) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public String getInfoGalleriXmlRpcUrl() {
				return RediaConfig.getInfoGalleriXmlRpcUrl(getString(R.string.infoGalleriXmlRpcUrlVersion));
			}
			
			@Override
			public String getUiLanguage() {
				// TODO Auto-generated method stub
				return null;
			}
		});
        // Ensure that image cache gets created
        try {
        	ImageCache.getInstance();
        }
        catch (RuntimeException e) {
        	Log.e(logTag, "Failed to create image cache: " + e.getMessage() + ". Closing activity.");
        	finish();
        	return;
        }
        /*
         * 

public class LibraryAppApplication extends Application implements UncaughtExceptionHandler {

	private static Context context;

	public void onCreate() {
		super.onCreate();
		Thread.setDefaultUncaughtExceptionHandler(this);
		LibraryAppApplication.context = getApplicationContext();
	}

	public static Context getAppContext() {
		return LibraryAppApplication.context;
	}

	public static void toast(int resId, int duration) {
		Toast.makeText(context, resId, duration==Toast.LENGTH_LONG ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT).show();
	}
	
	public static void toast(String message, int duration) {
		Toast.makeText(context, message, duration==Toast.LENGTH_LONG ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT).show();
	}

	public void uncaughtException(Thread thread, Throwable ex) {
		ErrorReport e = new ErrorReport();
		e.setException(ex);
		e.setEmail("");
		e.setDescription("Uncaught exception " + ex.getClass().toString());
		FogbugzErrorReporter.report(e);
	}
	
}
         */
        
        
        setContentView(R.layout.main);

        ((TextView)findViewById(R.id.splashVersionTextView)).setText("Version " + VersionUtils.getVersion());
        
	    ImageView wideLogoImageView = (ImageView)findViewById(R.id.splashImageView);
	    wideLogoImageView.setImageResource(ResourceUtils.getSplashLogoResourceId());
        
	    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	    
        final LibraryAppActivity parent = this;
        
        Log.d(LibraryAppActivity.logTag, "Checking if web service is still supported");

        XmlRpcClient.getInstance().isSupported(getResources().getText(R.string.customerId), getResources().getText(R.string.apiKey), new XmlRpcClientResultListener() {
			
			public void callFailed(String message) {
				// Starting app although call failed.
				// Network connection may be down
				AppApplication.toast(R.string.noNetworkText, Toast.LENGTH_LONG);
				launchFrontPage();
			}
			
			public void callCompleted(Object result) {
				Log.d(LibraryAppActivity.logTag, "Call to isSupported completed");
				XmlRpcResultDumper.dump(result);
				String supported = "false";
				try {
					supported = (String) result;
				} catch (ClassCastException e) {
					Log.w(LibraryAppActivity.logTag, "Failed to convert result of isSupported to boolan");
				}
				
				if (supported.equals("supportedOK")) {
					Log.d(LibraryAppActivity.logTag, "Good news chief, web service tells us it is still supported");					
					
					Observer tmpModelObserver = new Observer() {
						
						public void update(Observable observable, Object data) {
							if (InfoGalleriModel.getInstance().isUp()) {
								InfoGalleriModel.getInstance().removeInfoObjectsObserver(this);
								parent.launchFrontPage();
							} else {
								Log.d(LibraryAppActivity.logTag, "Received callback from InfoGalleriModel, which is not up yet. Continuing wait.");
							}
						}
					};
					
					Log.d(LibraryAppActivity.logTag, "Initializing InfoGalleriModel and waiting for it to report ready ...");
					
					if (InfoGalleriModel.getInstance().isUp()) {
						launchFrontPage();
						Log.d(LibraryAppActivity.logTag, "InfoGalleriModel is already up");
					} else {
						InfoGalleriModel.getInstance().addInfoObjectsObserver(tmpModelObserver);
						Log.d(LibraryAppActivity.logTag, "InfoGalleriModel is not up");
					}
				} else {
					Log.d(LibraryAppActivity.logTag, "Oh bugger, web service is no longer supported. Bailing out!");
					AlertDialog d = new AlertDialog.Builder(parent).create();
					d.setTitle("Oh bugger");
					d.setMessage("This application is out of date, please update it");
					d.setButton("Ok", new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface arg0, int arg1) {
							System.exit(1);
						}
					});
					d.show();
				}
			}
		});
    }
    
    private void launchFrontPage() {
		Intent intent = new Intent(this, FrontPageActivity.class);
		startActivity(intent);
		finish();
    }
    
    protected void onDestroy() {
    	super.onDestroy();
    	// Stop the tracker when it is no longer needed.
    	//tracker.stopSession();
    }
}